<template>
  <div>
    <i-dialog
      :title="'批量升级设备数据导入'"
      :visible="visible"
      width="642px"
      :close-on-click-modal="false"
      @close="outerClose"
    >
      <div>
        <LoadFile v-model="uploadData" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </span>
    </i-dialog>
  </div>
</template>
<script>
import LoadFile from '@/components/LoadFile'
import { deviceVersionUpBatch } from '@/api/device'
export default {
  name: 'BatchUpload',
  components: { LoadFile },
  data() {
    return {
      uploadData: [],
    }
  },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  methods: {
    refreshTable() {
      this.$emit('refreshTable')
    },
    outerClose() {
      this.$emit('update:visible', false)
    },
    validElementLength(params) {
      if (params.length > 10000) {
        return false
      }
      return true
    },
    handleBatchOta() {
      let deviceIds = []
      let batchTimeouts = []
      let deviceId
      let batchTimeout

      this.uploadData.forEach((item) => {
        item.DeviceID && deviceIds.push(item.DeviceID)
        item.BatchTimeOut && batchTimeouts.push(item.BatchTimeOut)
      })

      if (deviceIds.length === 0 && batchTimeouts.length === 0) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '请正确填写表格数据,设备IMEI号和设备超时时间是必须输入！',
        })
        return
      }

      if (deviceIds.length != batchTimeouts.length) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '请正确填写表格数据，设备IMEI号和设备超时时间需一一对应！',
        })
        return
      }

      if (!this.validElementLength(this.uploadData)) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '导入数据太大，请限制输入10000!',
        })
        return
      } else {
        deviceId = deviceIds.join('|')
        batchTimeout = batchTimeouts.join('|')
      }
      const loading = this.$loading({
        lock: true,
        text: '操作进行中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })
      deviceVersionUpBatch({
        batchTimeout: batchTimeout,
        deviceId: deviceId,
      }).then(
        () => {
          loading.close()
          this.$message({
            message: '批量升级设备数据导入成功',
            type: 'success',
          })
          this.outerClose()
          this.refreshTable()
        },
        () => {
          loading.close()
          this.outerClose()
          this.refreshTable()
        }
      )
    },
    submit() {
      this.handleBatchOta()
    },
  },
}
</script>
